﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace ClassLibrary1
{
    public class NetClient
    {
        NetworkStream _connection;

        public NetClient(string ipAddr)
        {
            TcpClient tcpclnt = new TcpClient();
            tcpclnt.Connect(ipAddr, 8001);
            _connection = tcpclnt.GetStream();
        }

        public void SendBoard(byte[,] board)
        {
            Byte[] data = FlattenBoard(board);
            _connection.Write(data, 0, data.Length);
        }

        private Byte[] FlattenBoard(byte[,] board)
        {
            Byte[] flat = new Byte[64];
            int index = 0;

            for (int i = 7; i >=0; i--)
            {
                for (int j = 7; j >=0; j--)
                {
                    if(board[i, j]==Game.blank)
                        flat[index] = Game.blank;
                    else if (board[i, j] == Game.red)
                        flat[index] = Game.black;
                    else if (board[i, j] == Game.black)
                        flat[index] = Game.red;
                    else if (board[i, j] == Game.redKing)
                        flat[index] = Game.blackKing;
                    else if (board[i, j] == Game.blackKing)
                        flat[index] = Game.redKing;

                    index++;
                }
            }

            return flat;
        }

        public byte[,] GetBoard()
        {
            Byte[] data = new Byte[256];
            try
            {
                int length = _connection.Read(data, 0, 100);
            }
            catch (SocketException)
            {
                return null;
            }

            return RecreateBoardLevels(data);
        }

        private byte[,] RecreateBoardLevels(Byte[] flatBoard)
        {
            Byte[,] board = new Byte[8, 8];

            int index = 0;
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    board[i, j] = flatBoard[index];
                    index++;
                }
            }

            return board;
        }

        public void Close()
        {
            _connection.Close();
        }
    }
}
